using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using Legacy.Core.SaveGameManagement;

namespace MMXSaveGameConverter
{
    internal sealed class SaveFileWriter : FileWriterBase
    {
        private readonly string _savePath;

        public SaveFileWriter(SaveGameViewItem item)
            : base(item)
        {
            _savePath = Path.ChangeExtension(item.FullPath, ".save");
        }

        public override void Write()
        {
            using (Stream output = File.Create(_savePath))
            {
                WriteFileMeta(output);
                WriteSaveGame(output, string.Empty);
                WriteScreenshot(output);
            }
        }

        private void WriteFileMeta(Stream output)
        {
            SaveFileMeta fileMeta = new SaveFileMeta(Item.Name);
            fileMeta.ToSave(output);
        }

        protected override void WriteScreenshot(Stream output)
        {
            long oldPosition = output.Position;
            output.WriteInt32(0);
            base.WriteScreenshot(output);
            long newPosition = output.Position;

            int length = (int)(newPosition - oldPosition - 4);
            output.Seek(oldPosition, SeekOrigin.Begin);
            output.WriteInt32(length);
            output.Seek(newPosition, SeekOrigin.Begin);
        }
    }
}